import { Location } from '@angular/common';
import { ChangeDetectorRef, Component, Input, OnInit, Output, ViewChild } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { AfMessageService, AfUpDownService } from '@core';
import { STColumn, STComponent } from '@delon/abc/st';
import { _HttpClient } from '@delon/theme';
import { copy } from '@delon/util';

import { CodeGenService } from '../../codegen.service';
import { ConstNamingRule, LangSourceType } from '../lang';
import { LangService } from '../lang.service';

@Component({
  selector: 'app-cg-lang-jpa-script',
  templateUrl: './lang-jpa-script.component.html',
  styleUrls: ['./lang-jpa-script.component.less']
})
export class LangJpaScriptComponent implements OnInit {
  namingRuleList = ConstNamingRule;

  sourceType: any = LangSourceType.database;
  sourceTable: any = undefined;
  sourceLabel: any = undefined;
  // 数据库名称或父节点名称
  sourceName: any = undefined;
  scriptDbType: any = 'mysql';

  isLoading = false;
  namingRule = 'same';

  packageName: any = 'com.af.business';
  moduleName: any = 'tmp';
  author: any = '';
  record: any;

  codeMirrorOptions = {
    lineNumbers: true,
    theme: 'dracula',
    mode: 'text/x-java',
    readOnly: true
  };

  constructor(
    private location: Location,
    private route: ActivatedRoute,
    private msg: AfMessageService,
    private codegen: CodeGenService,
    private cdr: ChangeDetectorRef,
    private langServ: LangService,
    private updownSrv: AfUpDownService
  ) {}

  ngOnInit(): void {
    const param = this.route.snapshot.queryParams;
    if (param && param['sourceType']) {
      this.initParamData(param);
      console.log(`param${JSON.stringify(param)}`);
    }
    if (this.record) {
      this.initParamData(this.record);
      console.log(`record${this.record}`);
    }
  }

  initParamData(param: any) {
    this.sourceType = param['sourceType'];
    this.sourceName = param['sourceName'];
    this.sourceTable = param['sourceTable'];
    this.namingRule = param['namingRule'];
    this.scriptDbType = param['scriptDbType'];
    this.sourceLabel = param['sourceLabel'];
  }

  public checkParam(): boolean {
    if (this.codegen.isEmpty(this.sourceName)) {
      this.msg.notice_warning('警告信息', `请选择数据源`);
      return false;
    }
    if (this.codegen.isEmpty(this.sourceTable)) {
      this.msg.notice_warning('警告信息', `请输入并选择表`);
      return false;
    }
    return true;
  }

  selectedIndex = 0;
  tableLoading = false;

  backPage() {
    this.location.back();
  }

  jpaEntityScripts: any[] = [];
  javaValue: any = '';
  public fetchJpaCode() {
    if (!this.checkParam()) {
      return;
    }
    this.selectedIndex = 2;

    this.isLoading = true;
    this.cdr.detectChanges();
    try {
      this.langServ
        .getJpaCodeList(this.sourceType, this.sourceName, this.sourceTable, this.namingRule, this.packageName, this.moduleName, this.author)
        .subscribe(body => {
          if (body.status) {
            const jpaScripts: any[] = body.data;
            if (jpaScripts !== null && jpaScripts.length >= 1) {
              this.jpaEntityScripts = jpaScripts[0].jpaEntityScripts;
            }
            this.jpaEntityScripts.forEach(entity => {
              if (entity.templateType == 'entity') {
                this.javaValue = entity.javaValue;
              }
            });
          } else {
            this.msg.notice_warning('查询文件', `无数据`);
          }
        });
    } finally {
      setTimeout(() => {
        this.isLoading = false;
        this.cdr.detectChanges();
      }, 1500);
    }
  }

  downloadJpaZip(record: any = {}) {
    this.cdr.detectChanges();
    try {
      const url = this.langServ.downloadJpaCodeZipUrl(
        this.sourceType,
        this.sourceName,
        this.sourceTable,
        this.namingRule,
        this.packageName,
        this.moduleName,
        this.author
      );
      this.updownSrv.downFile('get', url, null, null);
      // window.open(url);
    } finally {
      this.cdr.detectChanges();
    }
  }

  jpaSelectIndexChange($event: any) {
    this.jpaEntityScripts.forEach(entity => {
      if ($event == 0 && entity.templateType == 'entity') {
        this.javaValue = entity.javaValue;
        return;
      }
      if ($event == 1 && entity.templateType == 'repository') {
        this.javaValue = entity.javaValue;
        return;
      }
      if ($event == 2 && entity.templateType == 'service') {
        this.javaValue = entity.javaValue;
        return;
      }
      if ($event == 3 && entity.templateType == 'controller') {
        this.javaValue = entity.javaValue;
        return;
      }
    });
    this.cdr.detectChanges();
  }

  copyCode() {
    copy(this.javaValue);
    this.msg.msg_success('复制成功');
  }

  getSourceType() {
    if (this.sourceType == LangSourceType.database) {
      return `数据库/${this.sourceName}`;
    } else {
      return `元数据/${this.sourceName}`;
    }
  }
}
